import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Properties;

import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class WarehouseClient extends JFrame {
	private static final long serialVersionUID = 2822086383530097408L;
	private static InitialContext ic;
	private static Object objref;
	private static WarehouseInterface warehouse;
	private JMenuBar menuBar;
	private JMenu menu;
	private JMenuItem exit;
	private MainView mainView;

	public WarehouseClient(WarehouseInterface server) {
		menuBar = new JMenuBar();
		menu = new JMenu("Menu");
		menuBar.add(menu);
		exit = new JMenuItem("Exit");
		exit.addActionListener(new exitHandler());
		menu.add(exit);
		mainView = new MainView(server);

		this.setJMenuBar(menuBar);
		this.setContentPane(mainView);
	}

	class exitHandler implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			System.exit(0);
		}
	}

	public static void main(String[] helloClient) {
		JFrame frame = null;
		try {


			Properties env = new Properties();
			env.put("java.naming.factory.initial",
					"com.sun.jndi.cosnaming.CNCtxFactory");
			env.put("java.naming.provider.url", "iiop://localhost:2809");
			ic = new InitialContext(env);

			objref = ic.lookup("WarehouseService");

			warehouse = (WarehouseInterface) PortableRemoteObject.narrow(
					objref, WarehouseInterface.class);

			frame = new WarehouseClient(warehouse);
			frame.setBounds(200, 150, 800, 350);
		} catch (Exception ex) {
			frame = getErrorFrame(ex);
			frame.setBounds(200, 150, 500, 75);
		} finally {

			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setResizable(false);
			frame.setTitle("Warehouse Client");
			frame.setVisible(true);

		}
	}

	private static JFrame getErrorFrame(Exception ex) {
		JFrame frame = new JFrame();
		JPanel panel = new JPanel();
		String text = "<html>Er is een fout opgetreden bij het opstarten van de applicatie:<br>";
		text += "<font color=red>" + ex.getCause() + "</font></html>";
		JLabel label = new JLabel(text);
		panel.add(label);
		frame.setContentPane(panel);
		return frame;
	}

}
